import java.util.WeakHashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:何人亮
 * Date:2024-09-04
 * 15:14
 */

public class Test {
    public static void main(String[] args) {
        int[] array={1,4,62,3,1,67,2,6};
        mergeSortNor(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]+" ");
        }
    }

    public static void mergeSort(int[] array){
        mergeSort1(array,0,array.length-1);
    }

    private static void mergeSort1(int[] array, int left, int right) {
        if(left>=right){
            return;
        }
        int mid=(left+right)/2;
        mergeSort1(array,left,mid);          //分离
        mergeSort1(array,mid+1,right);  //分离
        merge(array,left,mid,right);        //合并
    }

    private static void merge(int[] array, int left, int mid, int right) {//数组有序合并
        int s1=left;
        int e1=mid;
        int s2=mid+1;
        int e2=right;
        int k=0;
        int[] num=new int[right-left+1];
        while (s1<=e1&&s2<=e2){
            if(array[s1]<=array[s2]){
                num[k++]=array[s1++];
            }
            if(array[s1]>array[s2]){
                num[k++]=array[s2++];
            }
        }
        while (s1<=e1){
            num[k++]=array[s1++];
        }
        while (s2<=e2){
            num[k++]=array[s2++];
        }
        for (int i = 0; i <k; i++) {
            array[left+i]=num[i];
        }
    }

    // 归并排序---非递归
    public static void mergeSortNor(int[] array){
        int gap=1;
        while (gap<=array.length){
            for (int i = 0; i < array.length; i=i+2*gap) {
                int left=i;
                int mid=left+gap-1;
                if(mid>array.length){
                    mid=array.length;
                }
                int right=mid+gap;
                if(right>array.length-1) {
                    right = array.length - 1;
                }

                merge(array,left,mid,right);
            }
            gap=gap*2;
        }
    }


}
